package cn.ddiancan.schedule.business.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

import cn.ddiancan.schedule.base.dao.ITaskTimerLogDao;
import cn.ddiancan.schedule.base.domain.TaskDTO;
import cn.ddiancan.schedule.base.domain.TaskLogVO;
import cn.ddiancan.schedule.base.service.ITaskTimerLogService;
import cn.ddiancan.schedule.task.event.TaskInvalidEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public abstract class AbastractScheduleExecutor implements IScheduleExecutor {

    @Autowired
    protected ITaskTimerLogService taskTimerLogService;

    @Autowired
    protected ApplicationContext applicationContext;

    public boolean beforeExecute(TaskDTO taskDTO, Runnable schedulingRunnable) {
        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        Date validStartDate = taskDTO.getValidStartDate();
        Date validEndDate = taskDTO.getValidEndDate();
        LocalDateTime startLocalDate = LocalDateTime.ofInstant(validStartDate.toInstant(), ZoneId.of("GMT+8"));
        LocalDateTime endLocalDate = LocalDateTime.ofInstant(validEndDate.toInstant(), ZoneId.of("GMT+8"));
        // 取消执行，关闭任务
        if (startLocalDate.isAfter(endLocalDate) || today.isAfter(endLocalDate)) {
            applicationContext.publishEvent(new TaskInvalidEvent(taskDTO.getScheduleCode(), schedulingRunnable));
            return false;
        }
        // TODO校验是否包含回调地址
        return true;
    }

    public void afterExecute(TaskLogVO taskLogVO) {
        taskTimerLogService.addTaskTimerLog(taskLogVO);
    }
}
